import { getCartList,setCartList } from '@/utils/storage'

export default {
	mutations: {
		updateGoodsChecked(state,isChecked){	// 处理是否全选功能
			state.cartList.forEach(g => g.goods_state = isChecked)
		},
		deleteGoods(state,goods_id){					// 删除商品处理函数
			state.cartList = state.cartList.filter(g => g.goods_id !== goods_id)
			// 持久化本地数据
			setCartList(state.cartList)
		},
		updateGoodsCount(state,obj){					// 处理更新商品的数量
			const goodsObj = state.cartList.find(g => g.goods_id === obj.goods_id)
			goodsObj.goods_count = obj.goods_count
			// 持久化本地数据
			setCartList(state.cartList)
		},
		updateGoodsSelectStatus(state,obj){		// 处理商品是否选中处理函数
			const goodsObj = state.cartList.find(g => g.goods_id === obj.goods_id)
			goodsObj.goods_state = obj.goods_state
			// 持久化本地数据
			setCartList(state.cartList)
		},
		addToCart(state,goods){		// 向 cartList 数组中添加数据
			const findGoods = state.cartList.find(g => g.goods_id === goods.goods_id)
			// 校验是否存在该商品
			if(!findGoods){
				state.cartList.push(goods)
			} else {
				findGoods.goods_count++;
			}
			console.log(state.cartList,'cartList')
			// 持久化本地数据
			setCartList(state.cartList)
		}
	},
	getters: {
		totalGoodsPrice(state){					// 统计商品价格
		 return	state.cartList.filter(g => g.goods_state).reduce((sum,g)=> sum + (g.goods_count * g.goods_price),0).toFixed(2)
		},
		checkedCount(state){				// 统计选中商品的数量
			return state.cartList.filter(g => g.goods_state).reduce((sum,g) => sum + g.goods_count,0)
		},
		totalGoodsCount(state){			// 统计购物车商品数量
			return state.cartList.reduce((sum,g)=> sum + g.goods_count,0)
		}
	},
	state(){
		return {
			cartList: getCartList(),		// 存储购物车列表数据数组
		}
	},
	namespaced: true		// 开启命名空间
}